package com.block.datapush.form.interceptor;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.LogFactory;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.util.HttpReturnUtil;
import com.block.datapush.form.service.IFormInfoService;
import com.block.db.entity.FormInfo;
import com.block.db.util.IdTypeEnum;
import com.block.db.util.SnowflakeUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 表单 第三方访问
 * 1.获取传输的手机号
 *
 */
public class OpenDataInterceptor implements HandlerInterceptor {

    private static final Logger log = LogFactory.getAppReq();
    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    IFormInfoService formInfoService;

    /**
     * 请求前置拦截
     *
     * @param request  请求体
     * @param response 响应体
     * @param handler
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String uri = request.getRequestURI();
        String ip= ServletUtil.getClientIP(request);
        try {

            String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            log.info("【渠道联登】【请求参数】【uri】{}【paramContent】{}", uri, paramContent);

            if (StrUtil.isEmpty(paramContent)){
                // 参数错误
                HttpReturnUtil.returnJson(response, ResultInfoVO.error("请求参数为空"));
                return false;
            }

            // 参数校验
            JSONObject paramObject = JSON.parseObject(paramContent);
            String channelId = paramObject.getString("channelId");
            // 需要判断渠道状态，需要进行渠道信息解密
            FormInfo formInfo = formInfoService.getEntityByChannelId(channelId);
            if (ObjectUtil.isEmpty(formInfo)){
                // 渠道信息为空
                HttpReturnUtil.returnJson(response, ResultInfoVO.error("渠道信息为空"));
                return false;
            }

            if (ObjectUtil.equal(formInfo.getDelFlag(), Integer.valueOf("1"))){
                // 渠道信息为空
                HttpReturnUtil.returnJson(response, ResultInfoVO.error("渠道信息不可用"));
                return false;
            }

            JSONObject tranData = null;
            try {
                String tranDataStr = paramObject.getString("tranData");
                tranData = JSON.parseObject(decrypt(tranDataStr, formInfo.getAesKey()));
            }catch (Exception exception){
                exception.printStackTrace();
            }

            if (ObjectUtil.isEmpty(tranData)){
                // 渠道信息为空
                HttpReturnUtil.returnJson(response, ResultInfoVO.error("业务参数为空"));
                return false;
            }

            String requestNo = SnowflakeUtil.getSnowflakeByTime(IdTypeEnum.COMMON);
            request.setAttribute("tranData", tranData);
            request.setAttribute("ip", ip);
            request.setAttribute("requestNo", requestNo);
            request.setAttribute("formInfo", formInfo);
            request.setAttribute("channelId", channelId);// 渠道信息
            return  true;
        } catch (Exception e){
            log.error("拦截器处理异常json...",e);
            HttpReturnUtil.returnJson(response, ResultInfoVO.error("处理异常：" + e.getMessage()));
            return  false;
        }
    }


    public static String decrypt(String content, String aesKey) throws Exception{
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");;
        SecretKeySpec skeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(Base64.decodeBase64(content));
        return new String(encrypted);
    }

    public static void main(String[] args) {
        System.out.println(RandomUtil.randomString(32).toUpperCase());
    }
}

